﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using FormControllers;
using AgencyEntityLib.BaseEntity;
using Ecopsy.DataTier;
using Ecopsy.Tools;

public partial class Agency_Frame : iPageController 
{
    #region Private

    private void BindTree()
    {
        bool isEnabled= true ;
        string sUrlKey= string.Empty ;


        /// Дерево оргструктуры цепляем только если стоит разрещение на просмотр списка сотрудников
        isEnabled = true;
        sUrlKey = "iFrameAdmin_Constractions";
        iPageController.SetPageUrl(ref sUrlKey, ref isEnabled);
        tvConstractions.DataSource = (isEnabled ? GetConstractionTreeSource() : null);  
        tvConstractions.DataBind();

        /// Дерево оргструктуры цепляем только если стоит разрещение на просмотр списка сотрудников
        isEnabled = true;
        sUrlKey = "iFrameAdmin_Employees";
        iPageController.SetPageUrl(ref sUrlKey, ref isEnabled); 
        tvAgencyTree.DataSource = (isEnabled?GetTreeSource(): null);
        tvAgencyTree.DataBind();

        TreeNode nd = new TreeNode();
        isEnabled = true;
        sUrlKey="iFrameAdmin_Discounts";
        SetPageUrl(ref sUrlKey, ref isEnabled);
        nd.Text = "<a class=TreeNode ID=Disconts_ href=\"#\"  onclick=\"showTreeBranch('" + sUrlKey + ".aspx','Disconts_');\"> Дисконтные программы </a>";
        if (isEnabled) tvAgencyTree.Nodes.Add(nd);

        nd = new TreeNode();
        isEnabled = true;
        sUrlKey = "iFrameAdmin_SurfaceGroups";
        SetPageUrl(ref sUrlKey, ref isEnabled);
        nd.Text = "<a class=TreeNode ID=Groups_ href=\"#\"  onclick=\"showTreeBranch('" + sUrlKey + ".aspx','Groups_');\"> Группы </a>";
        if (isEnabled)  tvAgencyTree.Nodes.Add(nd);

        nd = new TreeNode();
        isEnabled = true;
        sUrlKey = "iFarmeAdmin_AdressPrograms";
        SetPageUrl(ref sUrlKey, ref isEnabled);
        nd.Text = "<a class=TreeNode ID=Programs_ href=\"#\"  onclick=\"showTreeBranch('" + sUrlKey + ".aspx','Programs_');\"> Адресные программы </a>";
        if (isEnabled)  tvAgencyTree.Nodes.Add(nd);

        if (tvAgencyTree.Nodes.Count > 0)
        {
            tvAgencyTree.CollapseAll();

        }

        if (tvConstractions.Nodes.Count > 0)
        {
            tvConstractions.CollapseAll();
        }
    }


    #endregion

    #region Protected
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindTree();
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        CreateAgency();

    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        //string s= Master.GetSelectedNode();
        //wsAgency w = new wsAgency();
        //w.AddDepartment(s, "Новый элемент");
        //w.SaveAgency();
        //BindTree();
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        //string s = Master.GetSelectedNode();
        //wsAgency w = new wsAgency();
        //Department d = w.GetDepartment(s);        
        //w.RemoveDepartment (d.ID) ;
        //w.SaveAgency();
        //BindTree();

    }
    #endregion

    #region tools
    private void CreateAgency()
    {
        Agency ag = new Agency();
        ag.Name = "Первое московское";
        ag.ID = "1";
        Department a = new Department();
        a.Name = "Москва";


        Employeer empl = new Employeer();
        empl.FirstName = "Иванов";
        empl.SecondName = "Иван";
        empl.LastName = "Иванович";
        empl.DepartmentId = a.ID;



        empl = new Employeer();
        empl.FirstName = "Сидоров";
        empl.SecondName = "Тимофей";
        empl.LastName = "Тимофеевич";
        empl.DepartmentId = a.ID;


        Department child = new Department();
        child.Name = "Кутузовское отделение";
        child.ID = "2";


        Department child1 = new Department();
        child1.Name = "Проспект";
        child1.ID = "3";

        child.ChildNodes.Add(child1);
        a.ChildNodes.Add(child);


        ag.Department = a;
        ag.Save();

        CacheTools.ResetCache("1");


    }
    #endregion

    #region Источник для дерева  Agency_TreeDataSource

    private F_TreeDataSource GetTreeSource()
    {
        ///Получить дерево департаментов
        wsAgency ws = new wsAgency();
        Agency a = ws.GetAgency();
        TreeEntitySingle tree = (TreeEntitySingle)a.Department;


        // определить делегат поставляющий класс определяющий формат ноды в дереве
        Func<TreeEntitySingle, F_TreeDataSource.F_TreeDataSourceView.F_TreeHierarchyData> f = delegate(TreeEntitySingle _tr)
        {
            return (AgencyNodeItemFormatter)new AgencyNodeItemFormatter(_tr);
        };

        // вернуть древовидныйисточник данных
        return new F_TreeDataSource(tree, f);
    }
    public class AgencyNodeItemFormatter : F_TreeDataSource.F_TreeDataSourceView.F_TreeHierarchyData
    {
        public AgencyNodeItemFormatter(TreeEntitySingle obj) : base(obj) { }

        public override bool HasChildren
        {
            get
            {
                return true;
            }
        }

        public override F_TreeDataSource.F_TreeDataSourceView.F_TreeHierarchyData GetNewObj(TreeEntitySingle nd)
        {
            return new AgencyNodeItemFormatter(nd);
        }
        public override IHierarchicalEnumerable GetChildren()
        {
            Ecopsy.Tools.F_TreeDataSource.F_TreeDataSourceView.TreeHierarchicalEnumerable children = new F_TreeDataSource.F_TreeDataSourceView.TreeHierarchicalEnumerable();
            {
                string sid = _nd.ID.Replace("-", string.Empty);
                // формируем текст для настройки                           
                bool isEnabled = true;
                string sUrlKey = "iFrameAdmin_Employees";
                iPageController.SetPageUrl(ref sUrlKey, ref isEnabled); 
                TreeNode nn = new TreeNode();
                nn = new TreeNode();
                nn.Text = "<a class=TreeNode ID=Agency_Empl_" + _nd.ID + " href=\"#\"  onclick=\"showTreeBranch('" + sUrlKey + ".aspx?DepartmentID=" + _nd.ID + "','Agency_Empl_" + _nd.ID + "');\">  Сотрудники  </a>";
                if(isEnabled)  children.Add(new TreeNodeHierarchyData(nn));

                foreach (TreeEntitySingle n in _nd.ChildNodes)
                {
                    children.Add(GetNewObj(n));
                }
            }
            return children;
        }
        public override string ToString()
        {           
            Department a = (Department)_nd;
            string sAddBtn = "<img alt='' src='images/sort_up_red.gif' />";
            string sDelBtn = "<img alt='' src='images/sort_down_red.gif' />";
            string sOnclick="onclick=\"showTreeBranch('iFrameAdmin_EditAgency.aspx?DepartmentID=" + _nd.ID + "','Department_" + _nd.ID + "');";            
            bool bUserInRole = UserInRoleForSiteMapItem(GlobalConstants.SiteMapItem_EditDepartments);

            return                    
                "<a class=TreeNode ID=Department_" + _nd.ID + "href=\"#\" " + (bUserInRole ? sOnclick : "") + "  \"> " + a.Name + " </a>"
                +(bUserInRole?sAddBtn:"")
                + (bUserInRole ? sDelBtn : "") 
                ;
        }
        public override string Path
        {
            get
            {
                return _nd.ID;
            }
        }
        public override object Item
        {
            get
            {
                return _nd;
            }
        }


    }
   
    

    #endregion

    #region Источник для дерева типы конструкций
    private F_TreeDataSource GetConstractionTreeSource()
    {
        ///Получить дерево              
        TreeEntitySingle tree = (TreeEntitySingle)iPageController.TreeDictionaryContext.GetConstractionType();

        // определить делегат поставляющий класс определяющий формат ноды в дереве
        Func<TreeEntitySingle, F_TreeDataSource.F_TreeDataSourceView.F_TreeHierarchyData> f = delegate(TreeEntitySingle _tr)
        {
            return (AgencyConstractionNodeItemFormatter)new AgencyConstractionNodeItemFormatter(_tr);
        };

        // вернуть древовидныйисточник данных
        return new F_TreeDataSource(tree, f);
    }
    public class AgencyConstractionNodeItemFormatter : F_TreeDataSource.F_TreeDataSourceView.F_TreeHierarchyData
    {
        public AgencyConstractionNodeItemFormatter(TreeEntitySingle obj) : base(obj) { }

        public override bool HasChildren
        {
            get
            {
                return true;
            }
        }

        public override F_TreeDataSource.F_TreeDataSourceView.F_TreeHierarchyData GetNewObj(TreeEntitySingle nd)
        {
            return new AgencyConstractionNodeItemFormatter(nd);
        }
        public override IHierarchicalEnumerable GetChildren()
        {
            Ecopsy.Tools.F_TreeDataSource.F_TreeDataSourceView.TreeHierarchicalEnumerable children = new F_TreeDataSource.F_TreeDataSourceView.TreeHierarchicalEnumerable();
            {

                foreach (TreeEntitySingle n in _nd.ChildNodes)
                {
                    children.Add(GetNewObj(n));
                }
            }
            return children;
        }
        public override string ToString()
        {
            bool isEnabled = true;
            string sUrlKey = "iFrameAdmin_Constractions";
            iPageController.SetPageUrl(ref sUrlKey, ref isEnabled);

            TreeDictionaryItem a = (TreeDictionaryItem)_nd;
            return "<a class=TreeNode ID='" + _nd.ID + "' href=\"#\"   onclick=\"showTreeBranch('" + sUrlKey + ".aspx?ConstractionTypeID=" + _nd.ID + "','" + _nd.ID + "');\"> " + a.Name + " </a>";
        }
        public override string Path
        {
            get
            {
                return _nd.ID;
            }
        }
        public override object Item
        {
            get
            {
                return _nd;
            }
        }


    }
    #endregion

    protected void AgencyTree_TreeNodeDataBound(object sender, TreeNodeEventArgs e)
    {
        object s = sender;
    }

}
